package cn.s1995.sloth.common.core.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import lombok.experimental.UtilityClass;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * StringUtils
 *
 * @Author penf
 * @Description 字符串工具类
 * @Date 2018/08/03 15:41
 */
@UtilityClass
public class StringUtil {

    public static final String EMPTY = "";

    public static void main(String[] args) {
        // 5ace0b2afd7e22aa7533421def0e7f9c
        // System.out.println(DigestUtil.md5Hex("5ace0b2afd7e22aa7533421def0e7f9c5ace0b2afd7e22aa7533421def0e7f9c5ace0b2afd7e22aa7533421def0e7f9c"));
        // String code = Arrays.stream(NumberUtil.generateRandomNumber(0, 9, 4))
        //         .mapToObj(String::valueOf).collect(Collectors.joining());
        // System.out.println(code);
        //
        // System.out.println();
        //
        // String pattern = "/app/**";
        // String path = "/app/common/settings";
        // AntPathMatcher antPathMatcher = new AntPathMatcher();
        // boolean match = antPathMatcher.match(pattern, path);
        // System.out.println(antPathMatcher.match(pattern, path));
        // System.out.println(antPathMatcher.match("/v2/doc", "/v2/doc"));
        // System.out.println(antPathMatcher.match("/v2/doc", "/v2/do"));


        // Map<String, String> collect = Arrays.asList("1", "2").stream().collect(Collectors.toMap(String::valueOf, String::valueOf));
        // System.out.println(collect);
        // Map<String, String> map = Map.of("3", "3", "4", "4");
        // System.out.println(map);
        // collect.putAll(map);
        // System.out.println(collect);

        String number = "123456";
        System.out.println("123456".substring(0, number.length()));
        System.out.println(getValue("12345", 5));
    }


    /**
     * 字符串是否为null或空
     *
     * @param value
     * @return
     */
    public static boolean isEmpty(String value) {
        if (value == null) {
            return true;
        }
        return value.trim().isEmpty();
    }

    /**
     * 字符串是否不为null或空
     *
     * @param value
     * @return
     */
    public static boolean isNotEmpty(String value) {
        return !isEmpty(value);
    }


    /**
     * 是否是数字
     *
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        if (isEmpty(str)) {
            return false;
        }
        Pattern pattern = Pattern.compile("^[0-9]+(.[0-9]+)?$");
        Matcher isNum = pattern.matcher(str);
        return isNum.matches();
    }

    /**
     * 字符串转数组
     *
     * @param value     字符串
     * @param separator 分隔符
     * @return
     */
    public static String[] convertStringArray(String value, String separator) {
        if (isNotEmpty(value)) {
            return value.split(separator);
        }
        return null;
    }

    /**
     * 字符串转集合
     *
     * @param value     字符串
     * @param separator 分隔符
     * @return
     */
    public static List<String> convertList(String value, String separator) {
        String[] strings = convertStringArray(value, separator);
        if (strings != null) {
            List<String> list = new ArrayList<>(strings.length);
            boolean b = Collections.addAll(list, strings);
            return list;
        }
        return null;
    }


    /**
     * 图片Url字符串转为集合
     *
     * @param allUrl
     * @return
     */
    public static List<String> convertPictureList(String allUrl) {

        return convertList(allUrl, ",");
    }

    /**
     * 验证手机号码
     *
     * @param mobile
     * @return
     */
    public static boolean checkMobile(String mobile) {
        boolean flag;
        try {
            Pattern regex = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(17[0-9])|(18[0,5-9]))\\d{8}$");
            Matcher m = regex.matcher(mobile);
            flag = m.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    /**
     * 验证邮箱地址是否正确
     *
     * @param email
     * @return
     */
    public static boolean checkEmail(String email) {
        boolean flag;
        try {
            String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
            Pattern regex = Pattern.compile(check);
            Matcher matcher = regex.matcher(email);
            flag = matcher.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }


    /**
     * 判断字符串中是否包含中文
     *
     * @param str 待校验字符串
     * @return 是否为中文
     * @warn 不能校验是否为中文标点符号
     */
    public static boolean isContainChinese(String str) {
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        return m.find();
    }

    /**
     * 验证字符串内容是否包含下列非法字符<br>
     * `~!#%^&*=+\\|{};:'\",<>/?○●★☆☉♀♂※¤╬の〆
     *
     * @param content 字符串内容
     * @return 't'代表不包含非法字符，otherwise代表包含非法字符。
     */
    public static char validateLegalString(String content) {
        String illegal = "`~!#%^&*=+\\|{};:'\",<>/?○●★☆☉♀♂※¤╬の〆";
        char isLegalChar = 't';
        L1:
        for (int i = 0; i < content.length(); i++) {
            for (int j = 0; j < illegal.length(); j++) {
                if (content.charAt(i) == illegal.charAt(j)) {
                    isLegalChar = content.charAt(i);
                    break L1;
                }
            }
        }
        return isLegalChar;
    }

    /**
     * 特殊字符转义
     *
     * @param before
     * @return
     */
    public static String escapeChar(String before) {
        if (isNotEmpty(before)) {
            before = before.replaceAll("\\\\", "\\\\\\\\");
            before = before.replaceAll("_", "\\\\_");
            before = before.replaceAll("%", "\\\\%");
            before = before.replaceAll("'", "\\\\'");
        }
        return before;
    }

    /**
     * 校验字母和数字
     *
     * @param content
     * @return
     */
    public static boolean isWordAndNumber(String content) {
        if (isNotEmpty(content)) {
            String reg = "^[0-9a-zA-Z]*";
            return content.matches(reg);
        }

        return false;
    }

    /**
     * 随机小写字母和数字
     *
     * @return
     */
    public static String getRandomLowerLetter(int length) {
        String str = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(str.length());
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 随机大写字母和数字
     *
     * @return
     */
    public static String getRandomUpperLetter(int length) {
        String str = System.currentTimeMillis() + "ABCDEFGHIJKLMNOPQRSTUVWSYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(str.length());
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }


    /**
     * 获取字符串值（对象为null则返回空字符串）
     * <pre>
     *     ""       ->  ""
     *     "ABC"    ->  "ABC"
     *     null     ->  ""
     * </pre>
     *
     * @param value
     * @return
     */
    public static String getValueOrEmpty(Object value) {
        if (value == null) {
            return "";
        }
        return value.toString().trim();
    }


    /**
     * 获取字符串值，如果字符串长度大于目标长度，则截取目标长度
     * @param value
     * @param targetLength
     * @return
     */
    public static String getValue(CharSequence value, int targetLength) {
        if (value == null) {
            return null;
        }
        return value.subSequence(0, Math.min(value.length(), targetLength)).toString();
    }

    /**
     * 获取指定长度范围内的list
     * 循环处理：如果furnitureIntroduce拼接“,”组成的字符串超出数据库字段长度，则移除furnitureIntroduce最后一个元素，直到长度不超出数据库字段长度
     * @param list  数据
     * @param length 数据库字段长度
     * @return
     */
    public static List<String> getRangeList(List<String> list, long length) {
        if (CollUtil.isEmpty(list)) {
            return new ArrayList<>();
        }
        String comma = StrUtil.COMMA;
        String furnitureIntroduceStr = String.join(comma, list);
        if (furnitureIntroduceStr.length() > length) {
            while (furnitureIntroduceStr.length() > length) {
                list.remove(list.size() - 1);
                furnitureIntroduceStr = String.join(comma, list);
            }
        }
        return list;
    }


}
